/**
 * Created by zhaoyanzhi on 16-9-21.
 */
app.controller('shoppingCartPage', function ($scope, $location, $http,$q) {
    $scope.getUserId = function () {
        var userId = JSON.parse(localStorage.getItem("AV/RaXOd37qSYs8fKCN82nbC9zd-gzGzoHsz/currentUser")).objectId;
        return userId
    }
    $scope.showActuallyPaid=function(data){
        var  sumActuallyPaid=ShoppingCart.computeSumActuallyPaidPrice(data);
        if(sumActuallyPaid==0){
            $location.path("/productListPage")
        }else {
            $scope.actuallyPaid = sumActuallyPaid;
        }
    }
    $scope.showShoppingList=function(){
        var defer = $q.defer();
        var promise = defer.promise;
        var userId = $scope.getUserId();
        var user = AV.Object.createWithoutData('User', userId);
        var relation = user.relation('productInfo');
        var query = relation.query();
        promise.then(function(data){
            $scope.cartList=data ;
            $scope.showActuallyPaid(data);
        })
        defer.resolve( query.find().then(function(results){
                var data=[];
                for(var i=0;i<results.length;i++){
                    data.push(results[i].attributes)
                }
                return data
            }
        ));
    }
    $scope.showShoppingList();
    $scope.addButtonEvent=function(num,index) {
        var userId = $scope.getUserId();
        var user = AV.Object.createWithoutData('User', userId);
        var relation = user.relation('productInfo');
        var query = relation.query();
        query.find().then(function (results) {
            var goodsInfo = AV.Object.createWithoutData('GoodsInfo', results[index].id);
            var itemInfo = Item.computeItemCount(results[index], num);
            var itemInfo = Item.computeCostPrice(itemInfo);
            var promotion = new Promotion();
            var itemInfo = promotion.computePromotionCount(itemInfo);
            var itemInfo = promotion.computeSavePrice(itemInfo);
            var itemInfo = ShoppingCart.computeActuallyPaid(itemInfo);
            goodsInfo.set('count', itemInfo.attributes.count);
            goodsInfo.set('costPrice', JSON.stringify(itemInfo.attributes.costPrice));
            goodsInfo.set('promotionCount', itemInfo.attributes.promotionCount);
            goodsInfo.set('savePrice', itemInfo.attributes.savePrice);
            goodsInfo.set('actuallyPaid', JSON.stringify(itemInfo.attributes.actuallyPaid));
            if(itemInfo.attributes.count>0){
                goodsInfo.save();
            }else{
                goodsInfo.destroy();
            }
            $scope.showShoppingList();
        })
    }
    $scope.jumpPaymentPage=function(){
        $location.path("/paymentPage")
    }
})
